package server;

import catalina.MappedContext;
import catalina.MappedHost;
import catalina.Mapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**
     * 定义socket监听的端口号
     */
    private int port = -1;
    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();
    private Mapper mapper = new Mapper();
    private MappedHost host = new MappedHost();
    private MappedContext context = new MappedContext();

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
//        loadServlet();
        // 加载解析相关的配置，server.xml
        loadServerXmlConfig();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Minicat start on port：" + port);
        while (true) {
            Socket socket = serverSocket.accept();
//            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            RequestProcessor requestProcessor = new RequestProcessor(socket, port, mapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServerXmlConfig() {

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> serviceNodes = rootElement.selectNodes("//Service");
            for (Element serviceElement : serviceNodes) {
                // Connector.port
                Element connectorElement = (Element) serviceElement.selectSingleNode("Connector");
                port = Integer.parseInt(connectorElement.valueOf("@port"));

                // Engine
                List<Element> engineNodes = serviceElement.selectNodes("Engine");
                for (Element engineElement : engineNodes) {
                    List<Element> hostNodes = engineElement.selectNodes("Host");
                    for (Element hostElement : hostNodes) {
                        String name = hostElement.valueOf("@name");
                        String appBase = hostElement.valueOf("@appBase");

                        host = new MappedHost();
                        loadAppWebXmlConfig(appBase);
                        mapper.addHost(name, host);
                    }
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    private void loadAppWebXmlConfig(String filePath) {

        File file = new File(filePath);
        File[] files = file.listFiles();

        for (File childFile : files) {
            if (childFile.isDirectory()) {
                loadAppWebXmlConfig(childFile.getPath());

            } else {
                String fileName = childFile.getName();
                if ("web.xml".equals(fileName)) {

                    context = new MappedContext();
                    SAXReader saxReader = new SAXReader();

                    try (InputStream resourceAsStream = new BufferedInputStream(new FileInputStream(childFile.getAbsolutePath()))) {

                        Document document = saxReader.read(resourceAsStream);
                        Element rootElement = document.getRootElement();

                        List<Element> selectNodes = rootElement.selectNodes("//servlet");
                        for (int i = 0; i < selectNodes.size(); i++) {

                            Element element = selectNodes.get(i);
                            Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                            String servletName = servletNameElement.getStringValue();
                            Element servletClassNameElement = (Element) element.selectSingleNode("servlet-class");
                            String servletClassName = servletClassNameElement.getStringValue();

                            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                            /*** 使用urlLoader类加载器加载wabapps目录中的class文件，然后生成实例对象放入mapper中的wrapper ***/
                            File webAppClass = new File(childFile.getParent());
                            URLClassLoader urlLoader = new URLClassLoader(new URL[]{webAppClass.toURI().toURL()}, this.getClass().getClassLoader());
                            context.addWrapper(urlPattern, (HttpServlet) urlLoader.loadClass(servletClassName).getDeclaredConstructor().newInstance());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    host.addContext(childFile.getParentFile().getName(), context);
                }
            }
        }
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
